package com.foreknow.springboot.mapper;

import com.foreknow.springboot.po.Cart;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author xiaoming
 * @version jdk1.8
 * @date 2022/8/13 17:47
 * @function:
 */
//   表示当前的Mapper层交给Mybatis来实现
@Mapper
public interface CartMapper {
    /**
     * 根据用户编号查询此用户所有购物车信息​ 根据用户编号和商家编号，查询此用户购物车中某个商家的所有购物车信息
     *
     * @param cart
     * @return
     */
    public List<Cart> listCart(Cart cart);

    /**
     * 向购物车表中添加一条记录
     *
     * @param userId
     * @param businessId
     * @param foodId
     * @return
     */
    @Insert("insert into cart(foodId,businessId,userId,quantity) values(#{foodId},#{businessId},#{userId},1)")
    public int saveCart(String userId, Integer businessId, Integer foodId);

    /**
     * 根据用户编号、商家编号、食品编号更新数量
     *
     * @param userId
     * @param businessId
     * @param foodId
     * @param quantity
     * @return
     */
    @Update("update cart set quantity=#{quantity} where userId=#{userId} and businessId=#{businessId} and foodId=#{foodId}")
    public int updateCart(String userId, Integer businessId, Integer foodId, Integer quantity);

    /**
     * 根据用户编号、商家编号、食品编号删除购物车表中的一条食品记录​ 根据用户编号、商家编号删除购物车表中的多条条记录
     *
     * @param cart
     * @return
     * @throws
     */
    @DeleteProvider(type = CartSqlProvider.class, method = "removeCardByUserIdAndBusinessId")
    public int removeCart(Cart cart);

    class CartSqlProvider {
    //    public String listCart(Cart cart) {
    //        String sql = "select * from cart,business,food where cart.businessId=business.businessId and cart.foodId=food.foodId and cart.userId=#{userId}";
    //        if (cart.getBusinessId()!=null){
    //            sql+="and cart.businessId=#{businessId}";
    //        }
    //        return sql;
    //    }
    //
        public String removeCardByUserIdAndBusinessId(Cart cart) {
            String sql = "delete from cart where userId=#{userId} and businessId=#{businessId} ";
            if (cart.getFoodId() != null) {
                sql += "and foodId=#{foodId}";
            }
            return sql;
        }
    }
}
